<template>
    <div>
        <!-- 面包屑导航  -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }"
                >首页</el-breadcrumb-item
            >
            <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <h3>用户列表组件</h3>

        <el-card>
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input
                        @change="search"
                        @keydown.native.enter="search"
                        @clear="clear"
                        clearable
                        placeholder="请输入内容"
                        label-width="220px"
                        v-model="queryInfo.query"
                    >
                        <el-button
                            @click="search"
                            slot="append"
                            icon="el-icon-search"
                        ></el-button>
                    </el-input>
                </el-col>

                <el-col :span="4">
                    <el-button type="primary" icon="el-icon-plus" @click="openDialog">添加用户</el-button>
                </el-col>
            </el-row>

            <el-table :data="userList" border stripe>
                <el-table-column
                    label="序号"
                    type="index"
                    width="50"
                    align="center"
                ></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="{ row, $index }">
                        <el-switch active-color="#13ce66" v-model="row.mg_state" @change="changeState(row, $index)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="{ row, $index }">
                        <el-tooltip class="item" effect="dark" content="修改" placement="top-start">
                            <el-button @click="OpenUpdateDialog(row.id)" type="primary" icon="el-icon-edit" size="mini"></el-button>
                        </el-tooltip>

                        <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                            <el-button @click="deleteUser(row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
                        </el-tooltip>

                        <el-tooltip  class="item" effect="dark" content="分配角色" placement="top-start">
                            <el-button @click="openAssignRoleDialog(row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                :current-page="queryInfo.pagenum"
                :page-sizes="[3, 5, 10]"
                :page-size="queryInfo.pagesize"
                @size-change="handleSizeChange"
                @current-change="getUsersList"
                layout="prev, pager, next, jumper,->,sizes,total"
                :total="total"
            >
            </el-pagination>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="50%" @close="closeDialog">
            <el-form :model="addUserInfo" :rules="addUserRules" ref="addUserInfo" label-width="80px" >
                <el-form-item label="用户名:" prop="username">
                    <el-input v-model="addUserInfo.username"></el-input>
                </el-form-item>

                <el-form-item label="密码:" prop="password">
                    <el-input v-model="addUserInfo.password" type="password" show-password></el-input>
                </el-form-item>

                <el-form-item label="email:" prop="email">
                    <el-input v-model="addUserInfo.email"></el-input>
                </el-form-item>

                <el-form-item label="mobile:" prop="mobile">
                    <el-input v-model="addUserInfo.mobile"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改用户对话框 -->
        <el-dialog title="修改用户" :visible.sync="updataUserDialogVisible" width="50%" @close="closeUpdate">
            <el-form label-width="80px" :model="updataUser" ref="updataUserRef" :rules="updataUserRules">
                <el-form-item label="用户名:">
                    <el-input v-model="updataUser.username" :disabled="true"></el-input>
                </el-form-item>

                <el-form-item label="邮件:" prop="email">
                    <el-input v-model="updataUser.email"></el-input>
                </el-form-item>

                <el-form-item label="手机:" prop="mobile">
                    <el-input v-model="updataUser.mobile"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="updataUserDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updataUserFn(updataUser.id)">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配用户权限对话框 -->
        <el-dialog title="分配用户权限" :visible.sync="assignUserRoleDialogVisible"
            width="50%" @close="closeAssignUserDialog">
            <div>
                <p>当前的用户:{{userInfo.username}}</p>
                <p>当前的角色:{{userInfo.role_name}}</p>

                <p>
                    分配新角色:
                    <el-select v-model="selectRoleId" placeholder="请选择">
                        <el-option v-for="item in roleList" :key="item.id"
                            :label="item.roleName" :value="`${item.id}`">
                        </el-option>
                    </el-select>
                </p>

            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="assignUserRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="assignUserRoleFn()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'User',

  data () {
    var validateEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('邮箱不正确'))
      }
    }

    var validateMobile = (rule, value, callback) => {
      const regMobile = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/

      if (regMobile.test(value)) {
        return callback()
      } else {
        callback(new Error('手机号不正确'))
      }
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 3
      },
      userList: [],
      total: 0,
      addUserDialogVisible: false,

      addUserInfo: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },

      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ]
      },

      updataUserDialogVisible: false,

      updataUser: {
        username: '',
        email: '',
        mobile: ''
      },

      updataUserRules: {
        email: [

          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [

          { validator: validateMobile, trigger: 'blur' }
        ]
      },

      assignUserRoleDialogVisible: false,

      userInfo: {}, // 当前选中的需要分配权限的user

      roleList: [], // 获取用户所有角色

      selectRoleId: '' // 选择权限的id
    }
  },

  created () {
    this.getUsersList()
  },

  methods: {
    // 获取用户列表
    async getUsersList (pager = 1) {
      this.queryInfo.pagenum = pager
      const { data, meta } = await this.$http.user.getUserList(
        this.queryInfo
      )
      if (meta.status === 200) {
        this.userList = data.users
        this.total = data.total
      } else {
        console.log('获取用户列表接口错误')
      }
    },

    // 点击Pagination分页按钮
    handleSizeChange (pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getUsersList()
    },

    // 点击搜索按钮
    search () {
      this.$message.success('查询成功')
      this.getUsersList()
    },

    // 清空搜索框
    clear () {
      this.$message.success('查询成功')
      this.queryInfo.query = ''
      this.getUsersList()
    },

    // 点击Switch开口同步修改数据库中的数据
    async changeState (item) {
      const { data, meta } = await this.$http.user.chagneUserState(
        item.id,
        item.mg_state
      )

      if (meta.status === 200) {
        this.$message({
          message: '更新用户状态成功',
          type: 'success'
        })

        this.getUsersList()
      } else {
        this.$message({
          message: '更新用户状态失败',
          type: 'error'
        })

        item.mg_state = !item.mg_state
      }
    },

    // 点击添加用户按钮
    openDialog () {
      this.addUserDialogVisible = true

      this.addUserInfo = {
        username: '',
        password: '',
        email: '',
        mobile: ''
      }
    },

    // 关闭dialog
    closeDialog () {
      this.$refs.addUserInfo.resetFields()
    },

    // 添加用户操作
    addUser () {
      this.$refs.addUserInfo.validate(async vaild => {
        if (!vaild) {
          this.$message.error('请填写正确的信息')
          return
        };

        const { meta } = await this.$http.user.addUser(this.addUserInfo)
        if (meta.status === 201) {
          this.$message.success('新增用户成功')

          this.addUserDialogVisible = false

          this.getUsersList()
        } else {
          this.$message.error('请填写正确的信息')
        }
      })
    },

    // 修改用户操作
    async OpenUpdateDialog (id) {
      this.updataUserDialogVisible = true
      const { data, meta } = await this.$http.user.getUserById(id)
      if (meta.status === 200) {
        this.updataUser = data
      } else {
        this.$message.error('查询用户失败')
      }
    },

    // 关闭修改用户dialog
    closeUpdate () {
      this.$refs.updataUserRef.resetFields()
    },

    // 修改用户信息
    updataUserFn (id) {
      this.$refs.updataUserRef.validate(async (valid) => {
        if (valid) {
          const { meta } = await this.$http.user.updateUserById(id, { email: this.updataUser.email, mobile: this.updataUser.mobile })
          if (meta.status === 200) {
            this.$message.success('修改用户成功')
            this.updataUserDialogVisible = false
            this.getUsersList(this.queryInfo.pagenum)
          } else {
            this.$message.error('修改用户失败')
          }
        } else {
          this.$message.error('请输入正确数据')
          return false
        }
      })
    },

    // 删除用户
    async deleteUser (id) {
      const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (res === 'confirm') {
        const { meta } = await this.$http.user.deletUserById(id)
        console.log('meta: ', meta)

        if (meta.status === 200) {
          this.$message.success('删除成功')
          this.getUsersList(this.userList.length > 1 ? this.queryInfo.pagenum : this.queryInfo.pagenum - 1)
        } else {
          this.$message.error('删除失败')
        }
      }
    },

    // 打开分配用户权限对话框
    async openAssignRoleDialog (userInfo) {
      this.userInfo = userInfo

      const { data, meta } = await this.$http.user.getUserRoleList()
      if (meta.status === 200) {
        this.roleList = data
      }

      this.assignUserRoleDialogVisible = true
    },

    // 分配用户权限
    async assignUserRoleFn () {
      const { data, meta } = await this.$http.user.assignUserRole(this.userInfo.id, { rid: +this.selectRoleId })
      if (meta.status === 200) {
        this.$message.success('分配用户权限成功')
        this.getUsersList(this.queryInfo.pagenum)
        this.assignUserRoleDialogVisible = false
      } else {
        this.$message.error('分配用户权限失败')
      }
    },

    // 关闭分配用户权限对话框
    closeAssignUserDialog () {
      this.selectRoleId = ''
      this.userInfo = {}
      this.roleList = []
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
    margin-bottom: 20px;
}
.el-pagination {
    text-align: center;
    margin-top: 20px;
}
</style>
